<script setup>
import BaseInfo from '@v/data-converge/indicator-manage/add/BaseInfo.vue'
import Index from '@v/data-converge/indicator-manage/add/Index.vue'
import { computed, onMounted, ref } from 'vue'
import {
  addOrUpdateBaseIndex,
  publishBaseIndex,
  queryBaseIndexDetail,
} from '@api/city-index'

import { getCurrentInstance } from 'vue'
import { Message } from 'element-ui'
import { isFunction } from 'lodash'
import { PERMISSIONS } from '@/common/user'

const vm = getCurrentInstance()

const route = vm.proxy.$route
const router = vm.proxy.$router
const currentUser = vm.proxy.$store.state.user.currentUser
const { params, query } = route
const id = ref(params.id)
const status = ref(query.remark)

const saveLoading = ref(false)

const disabled = computed(() => {
  return !!status.value
})

const baseInfoRef = ref()

const indexRef = ref()

const handleCancel = () => {
  router.go(-1)
}

const itemValidate = (item) => {
  const information = item.indexInformationRel
  const indexType = information.indexType
  const indexUnit = information.indexUnit
  if (!indexUnit) {
    return false
  }
  let keyList = []
  let flag = true
  if (indexType === '区间型') {
    keyList = ['evaluateResult', 'moreThan', 'lessThan']
  } else if (indexType === '底线型') {
    keyList = ['evaluateResult', 'lessThan']
  } else if (indexType === '目标型') {
    keyList = ['evaluateResult', 'moreThan']
  }
  const indexEvaluateRels = item.indexEvaluateRels
  if (indexEvaluateRels.length && keyList.length) {
    flag = indexEvaluateRels.every((item) => {
      return keyList.every((key) => {
        return !!item[key] || item[key] === 0
      })
    })
  }
  return flag
}

const catalogInfoValidate = (info) => {
  const len = info.length
  for (let i = 0; i < len; i++) {
    const item = info[i]
    if (item.level === 3) {
      const isValid = itemValidate(item)
      if (!isValid) {
        return false
      }
    } else {
      const isValid = catalogInfoValidate(item.children || [])
      if (!isValid) {
        return false
      }
    }
  }
  return true
}

const handleSave = (cb) => {
  baseInfoRef.value.validate().then((valid) => {
    if (valid) {
      saveLoading.value = true
      const baseInfo = baseInfoRef.value.getValues()
      const indexInfo = indexRef.value.getValues()
      indexRef.value.setChoose(true)
      const data = {
        indexBaseTemplateInfo: baseInfo,
        indexCatalogInfos: indexInfo,
      }
      // console.log(catalogInfoValidate(indexInfo))
      if (!catalogInfoValidate(indexInfo)) {
        Message.error('指标信息填写不完整！')
        saveLoading.value = false
        indexRef.value.setChoose(false)
        return
      }
      addOrUpdateBaseIndex(data)
        .then((res) => {
          if (res.success) {
            // console.log(res.data)
            Message.success('保存成功！')
            const pkid = res.data.pkid
            const refId = res.data.refId
            if (!isFunction(cb)) {
              if (id.value) {
                //
              } else {
                id.value = pkid
                router.replace({
                  path: `/data-converge/indicator-manage-edit/${pkid}`,
                  query: {
                    pkid: pkid,
                    remark: status.value || 0,
                  },
                })
              }
              getData(pkid, refId)
            } else {
              getData(pkid, refId)
              cb(pkid)
            }
            // router.go(-1)
          } else {
            indexRef.value.setChoose(false)
            Message.error(res.message)
          }
        })
        .finally(() => {
          saveLoading.value = false
        })
    }
  })
}

const handlePublish = () => {
  vm.proxy
    .$confirm('发布后将不可修改，是否确认发布？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      // const baseInfo = baseInfoRef.value.getValues()
      handleSave((pkid) => {
        publishBaseIndex(pkid, 1).then((res) => {
          if (res.success) {
            // console.log(res.data)
            Message.success('发布成功！')
            router.go(-1)
          }
        })
      })
      // const pkid = baseInfo.pkid
    })
    .catch(() => {})
}

const getData = (id, refId) => {
  queryBaseIndexDetail(id).then((res) => {
    if (res.success) {
      const { indexBaseTemplateInfo, indexCatalogInfos } = res.data
      baseInfoRef.value.inputData(indexBaseTemplateInfo)
      indexRef.value.inputData(indexCatalogInfos, refId)
      // console.log(res.data)
    }
  })
}

onMounted(() => {
  if (id.value) {
    getData(id.value)
  }
})
</script>

<template>
  <div class="add-task">
    <div class="nav">
      <div class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/data-converge/indicator-manage' }"
            ><span class="breadcrumb-title">列表</span></el-breadcrumb-item
          >
          <el-breadcrumb-item>新增体系</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    <div class="content">
      <div class="content-main">
        <base-info ref="baseInfoRef" :disabled="disabled" />
        <div class="divider" />
        <index ref="indexRef" :disabled="disabled" />
      </div>
      <div class="buttons">
        <el-button class="cancel" @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          v-if="
            !disabled && currentUser?.hasPermission(PERMISSIONS.基础指标保存)
          "
          class="save"
          @click="handleSave"
          :loading="saveLoading"
        >
          {{ currentUser?.getButtonName(PERMISSIONS.基础指标保存) }}
        </el-button>
        <el-button
          type="primary"
          v-if="
            !disabled &&
            status != 1 &&
            currentUser?.hasPermission(PERMISSIONS.基础指标发布)
          "
          class="publish"
          @click="handlePublish"
        >
          {{ currentUser?.getButtonName(PERMISSIONS.基础指标发布) }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.add-task {
  width: calc(100% - 40px);
  height: calc(100% - 40px);
  padding: 20px;
  background-color: rgba(244, 248, 254, 1);

  .nav {
    height: 40px;
    border-radius: 2px;

    .breadcrumb {
      height: 40px;
      padding: 15px 0 10px 0;
      box-sizing: border-box;

      &-title {
        position: relative;
        margin-left: 11px;
        height: 21px;
        font-size: 15px;

        &::before {
          content: '';
          width: 5px;
          height: 16px;
          background: #10a6dd;
          border-radius: 3px;
          margin-right: 4px;
          display: inline-block;
          position: absolute;
          top: 50%;
          left: -11px;
          transform: translateY(-50%);
        }
      }
    }

    .divider {
      height: 1px;
      background: #e7f0ff;
      border-radius: 1px 1px 0px 0px;
    }
  }

  .content {
    width: calc(100% - 40px);
    height: calc(100% - 70px);
    position: absolute;
    top: 65px;
    bottom: 0;

    .divider {
      width: 100%;
      height: 1px;
      background: #e7f0ff;
      border-radius: 1px 1px 0px 0px;
      margin: 20px 0;
    }

    .content-main {
      height: calc(100% - 100px);
      background: #ffffff;
      box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);
      border-radius: 2px;
      padding: 13px 16px 13px 16px;
      overflow-y: auto;
    }

    .buttons {
      padding: 10px;
      display: flex;
      justify-content: center;
      background: #ffffff;
      box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);

      .el-button {
        width: 110px;
      }

      .cancel {
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #e7f0ff;
        font-weight: 400;
        font-size: 16px;
        color: #8894a8;
      }

      .save {
        //background: #10a6dd;
        border-radius: 4px;
        //color: #ffffff;
      }

      .publish {
        //background: #ffffff;
        border-radius: 4px;
        //color: #10a6dd;
        //border: 1px solid #10a6dd;
      }
    }
  }
}
</style>
